//
//  NSObject+BuildUIElement.m
//  Test
//
//  Created by WUwei on 17/5/1.
//  Copyright © 2017年 WUwei. All rights reserved.
//

#import "NSObject+BuildUIElement.h"
#import <WebKit/WebKit.h>
#import <AVFoundation/AVFoundation.h>


@implementation NSObject (BuildUIElement)

#pragma mark -
#pragma mark -------------------------------- build UI Element -------------------------------
#pragma mark -

- (UIButton *)ww_buildButton:(NSString *)title fontSize:(NSInteger)fontSize titleColor:(UIColor *)titleColor normalImage:(NSString *)normalImage target:(id)target selector:(SEL)selector toSuperView:(UIView *)superView {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:fontSize];
    [button setImage:[UIImage imageNamed:normalImage] forState:UIControlStateNormal];
    [button setTitleColor:titleColor forState:UIControlStateNormal];
    
    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    [superView addSubview:button];
    return button;
}

- (UIButton *)ww_buildImageButtonWithNormalImage:(NSString *)normalImage selectedImage:(NSString *)selectedImage target:(id)target selector:(SEL)selector toSuperView:(UIView *)superView {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:normalImage] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:selectedImage] forState:UIControlStateSelected];
    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    [superView addSubview:button];
    return button;
}

- (UIButton *)ww_buildTitleButton:(NSString *)title color:(UIColor *)color fontSize:(NSInteger )fontSize target:(id)target selector:(SEL)selector toSuperView:(UIView *)superView {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:fontSize];
    [button setTitleColor:color forState:UIControlStateNormal];
    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    [superView addSubview:button];
    return button;
}

- (UILabel *)ww_buildLabel:(NSString *)text fontSize:(NSInteger)fontSize color:(UIColor *)color bgColor:(UIColor *)bgColor alignment:(NSTextAlignment)alignment lines:(NSInteger)lines toSuperView:(UIView *)superView {
    UILabel *label = [UILabel new];
    label.backgroundColor = bgColor;
    label.text = text;
    label.textColor = color;
    label.textAlignment = alignment;
    label.font = [UIFont systemFontOfSize:fontSize];
    label.numberOfLines = lines;
    label.lineBreakMode = NSLineBreakByTruncatingTail;
    [superView addSubview:label];
    return label;
}


- (UIImageView *)ww_buildImageViewWithImage:(NSString *)image contentMode:(UIViewContentMode)contentMode toSuperView:(UIView *)superView {
    UIImageView *imageView = [UIImageView new];
    imageView.contentMode = contentMode;
    imageView.clipsToBounds = YES;
    imageView.image = [UIImage imageNamed:image];
    [superView addSubview:imageView];
    return imageView;
    
}


- (UITextField *)ww_buildTextField:(NSString *)content fontSize:(NSInteger )fontSize textColor:(UIColor *)textColor delegate:(id)delegate leftView:(UIView *)leftView toSuperView:(UIView *)superView {
    UITextField *textField = [UITextField new];
    textField.backgroundColor = [UIColor whiteColor];
    textField.delegate = delegate;
    textField.text = content;
    textField.textColor = textColor;
    textField.textAlignment = NSTextAlignmentLeft;
    textField.font = [UIFont systemFontOfSize:fontSize];
    textField.clearButtonMode = UITextFieldViewModeAlways;
    textField.leftView = leftView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    [superView addSubview:textField];
    return textField;
}

- (UITextView *)ww_buildTextView:(NSString *)content fontSize:(NSInteger )fontSize textColor:(UIColor *)textColor bgColor:(UIColor *)bgColor delegate:(id)delegate inputAccessoryView:(UIView *)inputAccessoryView returnKeyType:(UIReturnKeyType)returnKeyType contentInset:(UIEdgeInsets)contentInset toSuperView:(UIView *)superView {
    UITextView *textView = [UITextView new];
    textView.textColor = textColor;
    textView.textContainerInset = contentInset;
    textView.font = [UIFont systemFontOfSize:fontSize];
    textView.returnKeyType = returnKeyType;
    textView.autocapitalizationType = UITextAutocapitalizationTypeNone;
    textView.autocorrectionType = UITextAutocorrectionTypeNo;
    textView.inputAccessoryView = inputAccessoryView;
    textView.delegate = delegate;
    textView.text = content;
    textView.backgroundColor = bgColor;
    [superView addSubview:textView];
    return textView;
}


// searchBar
- (UISearchBar *)ww_buildSearchBarWithPlaceholder:(NSString *)placeholder height:(CGFloat)height innerBgColor:(UIColor *)innerBgColor outterWrappedColor:(UIColor *)outterWrappedColor fontSize:(NSInteger )fontSize textColor:(UIColor *)textColor borderColor:(UIColor *)borderColor borderWidth:(NSInteger)borderWidth filterImage:(NSString *)filterImage delegate:(id)delegate  cornerRadius:(CGFloat)cornerRadius cursorColor:(UIColor *)cursorColor toSuperView:(UIView *)superView {
    
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.placeholder = placeholder;
    searchBar.delegate = delegate;
    [searchBar setImage:[UIImage imageNamed:filterImage]
       forSearchBarIcon:UISearchBarIconSearch
                  state:UIControlStateNormal];
    
    searchBar.layer.borderWidth = borderWidth;
    searchBar.layer.cornerRadius = cornerRadius;
    searchBar.layer.masksToBounds = YES;
    
    
    searchBar.layer.borderColor = borderColor.CGColor;
    searchBar.barTintColor = outterWrappedColor; // 外部包裹的颜色
    searchBar.tintColor = cursorColor; // 闪动的光标的颜色
    [searchBar setBackgroundImage:ww_imageWithColor(innerBgColor, height)];
    [searchBar setBackgroundColor:outterWrappedColor];
    [searchBar setSearchFieldBackgroundImage:ww_imageWithColor(innerBgColor, height) forState:UIControlStateNormal];
    
    
    return searchBar;
}

UIImage* ww_imageWithColor(UIColor* color, CGFloat height) {
    CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
    UIGraphicsBeginImageContext(r.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, r);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}


- (UIScrollView *)ww_buildScrollView:(id)delegate contentWidth:(CGFloat)contentWidth contentHeight:(CGFloat)contentHeight pagingEnabled:(BOOL)pagingEnabled bounces:(BOOL)bounces verticalIndicator:(BOOL)verticalIndicator horizonIndicator:(BOOL)horizonIndicator toSuperView:(UIView *)superView {
    UIScrollView *scrollView = [UIScrollView new];
    scrollView.delegate = delegate;
    scrollView.bounces = bounces;
    scrollView.scrollEnabled = YES;
    scrollView.pagingEnabled = pagingEnabled;
    scrollView.showsVerticalScrollIndicator = verticalIndicator;
    scrollView.showsHorizontalScrollIndicator = horizonIndicator;
    scrollView.contentSize = CGSizeMake(contentWidth, contentHeight);
    scrollView.backgroundColor = [UIColor clearColor];
    [superView addSubview:scrollView];
    return scrollView;
}

- (UITableView *)ww_buildTableViewWithStyle:(UITableViewStyle)style delegate:(id)delegate scrollIndicator:(BOOL)scrollIndicator toSuperView:(UIView *)superView estimateHeight:(BOOL)estimateHeight rowHeight:(CGFloat)rowHeight zeroMarginSeparator:(BOOL)zeroMarginSeparator cellClasses:(Class)cellClass, ... NS_REQUIRES_NIL_TERMINATION {
    UITableView *tableView = [[UITableView new] initWithFrame:CGRectZero style:style];
    
    tableView.delegate = delegate;
    tableView.dataSource = delegate;
    
    if (estimateHeight) {
        tableView.rowHeight = UITableViewAutomaticDimension;
        tableView.estimatedRowHeight = rowHeight;
    }else if(rowHeight != 0){
        tableView.rowHeight = rowHeight;
    }
    
    if (zeroMarginSeparator) {
        tableView.separatorInset = UIEdgeInsetsZero;
        if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
            [tableView setLayoutMargins:UIEdgeInsetsZero];
        }
    }
    
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = scrollIndicator;
    tableView.separatorInset = UIEdgeInsetsZero;
    tableView.tableFooterView = [UIView new];
    
    NSMutableArray *argvs = [NSMutableArray array];
    va_list args;
    va_start(args, cellClass);
    if (cellClass) {
        [argvs addObject:cellClass];
        while (1) {
            Class otherArgs = va_arg(args, Class);
            if(otherArgs == nil) {
                break;
            } else {
                [argvs addObject:otherArgs];
            }
        }
    }
    va_end(args);
    for (Class class in argvs) {
        [tableView registerClass:class forCellReuseIdentifier:NSStringFromClass(class)];
    }
    [superView addSubview:tableView];
    return tableView;
}

- (UICollectionView *)ww_buildCollectionViewWithDelegate:(id)delegate itemWidth:(CGFloat)width itemHeight:(CGFloat)itemHeight  InteritemSpacing:(CGFloat)InteritemSpacing lineSpacing:(CGFloat)lineSpacing headerSize:(CGSize)headerSize footerSize:(CGSize)footerSize direction:(UICollectionViewScrollDirection)direction showsScrollIndicator:(BOOL)showsScrollIndicator toSuperView:(UIView *)superView cellClasses:(Class)cellClass, ... NS_REQUIRES_NIL_TERMINATION {
    
    UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
    layout.itemSize = CGSizeMake(width, itemHeight);
    layout.minimumInteritemSpacing = InteritemSpacing;
    layout.minimumLineSpacing = lineSpacing;
    layout.headerReferenceSize = headerSize;
    layout.footerReferenceSize = footerSize;
    layout.scrollDirection = direction;
    
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    [superView addSubview:collectionView];
    collectionView.delegate = delegate;
    collectionView.dataSource = delegate;
    collectionView.showsHorizontalScrollIndicator = showsScrollIndicator;
    
    NSMutableArray *argvs = [NSMutableArray array];
    va_list args;
    va_start(args, cellClass);
    if (cellClass) {
        [argvs addObject:cellClass];
        while (1) {
            Class otherArgs = va_arg(args, Class);
            if(otherArgs == nil) {
                break;
            } else {
                [argvs addObject:otherArgs];
            }
        }
    }
    va_end(args);
    for (Class class in argvs) {
        [collectionView registerClass:class forCellWithReuseIdentifier:NSStringFromClass(class)];
    }
    return collectionView;
}


- (UICollectionView *)ww_buildCollectionViewWithLayout:(UICollectionViewLayout *)layout  toSuperView:(UIView *)superView delegate:(id)delegate cellClasses:(Class)cellClass, ... NS_REQUIRES_NIL_TERMINATION {
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    [superView addSubview:collectionView];
    collectionView.delegate = delegate;
    collectionView.dataSource = delegate;
    NSMutableArray *argvs = [NSMutableArray array];
    va_list args;
    va_start(args, cellClass);
    if (cellClass) {
        [argvs addObject:cellClass];
        while (1) {
            Class otherArgs = va_arg(args, Class);
            if(otherArgs == nil) {
                break;
            } else {
                [argvs addObject:otherArgs];
            }
        }
    }
    va_end(args);
    for (Class class in argvs) {
        [collectionView registerClass:class forCellWithReuseIdentifier:NSStringFromClass(class)];
    }
    return collectionView;
}

- (UINavigationController *)ww_buildTabAndNaviVCWithVC:(UIViewController *)VC normalImg:(NSString *)normalImg selectedImg:(NSString *)selectedImg title:(NSString *)title {
    UIImage *normal = [UIImage imageNamed:normalImg];
    UIImage *selected = [UIImage imageNamed:selectedImg];
    VC.tabBarItem = [[UITabBarItem alloc] initWithTitle:title image:normal selectedImage:selected];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:VC];
    return navi;
}

- (WKWebView *)ww_buildWKWebViewWithDelegate:(id)delegate minFontSize:(NSInteger )minFontSize toSuperView:(UIView *)superView jsMessages:(NSString *)jsMessages, ... NS_REQUIRES_NIL_TERMINATION {

    WKWebViewConfiguration *config = [WKWebViewConfiguration new];
    config.preferences = [WKPreferences new];
    config.preferences.minimumFontSize = minFontSize;
    config.preferences.javaScriptEnabled = YES;
    config.processPool = [WKProcessPool new];
    // 默认是不能通过JS自动打开窗口的，必须通过用户交互才能打开
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    
    // 通过js与webview内容交互配置
    config.userContentController = [WKUserContentController new];
    //注入JS对象名称ZhangliangTest,当JS
    
    NSMutableArray *argvs = [NSMutableArray array];
    va_list args;
    va_start(args, jsMessages);
    if (jsMessages) {
        [argvs addObject:jsMessages];
        while (1) {
            NSString *otherArgs = va_arg(args, NSString *);
            if(otherArgs == nil) {
                break;
            } else {
                [argvs addObject:otherArgs];
            }
        }
    }
    va_end(args);
    for (NSString *jsMessage in argvs) {
        [config.userContentController addScriptMessageHandler:delegate name:jsMessage];
    }
    
    WKWebView *webview = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    webview.UIDelegate = delegate;
    webview.navigationDelegate = delegate;
    webview.allowsBackForwardNavigationGestures = YES;
//    [webview addObserver:delegate forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    webview.clipsToBounds = YES;
    webview.scrollView.clipsToBounds = NO;
    [superView addSubview:webview];
    
    return webview;
}

- (NSMutableAttributedString *)ww_buildAttributedString:(NSString *)string lineSpacing:(CGFloat)lineSpacing font:(UIFont *)font color:(UIColor *)color {
    NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
    [style setLineSpacing:lineSpacing];
    NSDictionary *attributes = @{NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName: style, NSFontAttributeName: font};

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string attributes:attributes];
    return attributedString;
    
}

- (void)ww_addObserveNotificationWithSelector:(SEL)selector names:(NSString *)names, ... NS_REQUIRES_NIL_TERMINATION {
    NSMutableArray *argvs = [NSMutableArray array];
    va_list args;
    va_start(args, names);
    if (names) {
        [argvs addObject:names];
        while (1) {
            NSString *otherArgs = va_arg(args, NSString *);
            if(otherArgs == nil) {
                break;
            } else {
                [argvs addObject:otherArgs];
            }
        }
    }
    va_end(args);
    for (NSString *name in argvs) {
       [[NSNotificationCenter defaultCenter] addObserver:self selector:selector name:name object:nil];
    }
    
}

- (void)ww_buildViewWithBgColor:(UIColor *)bgColor toSuperView:(UIView *)superView {
    UIView *view = [UIView new];
    [superView addSubview:view];
    view.backgroundColor = bgColor;
}

- (void)ww_roundTheView:(UIView *)view radius:(NSInteger )radius borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor {
    [view.layer setCornerRadius:(radius)];
    [view.layer setMasksToBounds:YES];
    [view.layer setBorderWidth:(borderWidth)];
    [view.layer setBorderColor:[borderColor CGColor]];
}

- (void)ww_activeTheView:(UIView *)view target:(id)target selector:(SEL)selector {
    view.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:selector];
    [view addGestureRecognizer:tap];
}

#pragma mark -
#pragma mark -------------------------------- string -------------------------------
#pragma mark -


NSString *ww_clockTimeWithDuration(long time) {
    if (time < 59*60+59) {
        return [NSString stringWithFormat:@"%02ld:%02ld",time/60,time%60];
    }
    return [NSString stringWithFormat:@"%02ld:%02ld:%02ld",time/3600,(time%3600)/60,(time%3600)%60];
}


#pragma mark -
#pragma mark -------------------------------- color -------------------------------
#pragma mark -

UIColor *ww_colorWithHexString(NSString *stringHex) {
    NSScanner *scanner = [NSScanner scannerWithString:stringHex];
    unsigned hexNum;
    if (![scanner scanHexInt:&hexNum]) return nil;
    int r = (hexNum >> 16) & 0xFF;
    int g = (hexNum >> 8) & 0xFF;
    int b = (hexNum) & 0xFF;
    return [UIColor colorWithRed:r / 255.0f
                           green:g / 255.0f
                            blue:b / 255.0f
                           alpha:1.0f];
}

UIColor *ww_randomColor() {
    CGFloat red =  (CGFloat)random()/(CGFloat)RAND_MAX;
    CGFloat blue = (CGFloat)random()/(CGFloat)RAND_MAX;
    CGFloat green = (CGFloat)random()/(CGFloat)RAND_MAX;
    return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}

UIColor *ww_colorWithRGB(NSInteger r, NSInteger g, NSInteger b) {
    return [UIColor colorWithRed:r / 255.f green:g / 255.f blue:b / 255.f alpha:1.f];
}

UIColor *ww_colorWithRGBA(NSInteger r, NSInteger g, NSInteger b, NSInteger a) {
    return [UIColor colorWithRed:r / 255.f green:g / 255.f blue:b / 255.f alpha:a];
}

#pragma mark -
#pragma mark -------------------------------- otherTools -------------------------------
#pragma mark -

// 跳转到APP自己的设置：
void ww_gotoAppSetting() {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }
}

// 判断是否安装了某个APP, urlString 的格式@"wei://wer.yt4.we"：
BOOL ww_hasApp(NSString *urlString) {
     return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]];
}
// 打开某个APP:
void ww_gotoApp(NSString *urlString) {
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
    }
}

// 显示/隐藏 状态栏
void ww_hideStatusBar(BOOL hidden) {
    [[UIApplication sharedApplication] setStatusBarHidden:hidden];
}


// 显示/隐藏 网络请求菊花
void ww_showNetworkIndicator(BOOL show) {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:show];
    
}

//- (void)ww_showNaviBar:(BOOL)show {
//   [self.navigationController setNavigationBarHidden:!show];
//}



// 判断系统版本
CGFloat ww_version() {
    return [[[UIDevice currentDevice] systemVersion] floatValue];
}

BOOL ww_iOS7() {
    return (([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0)? (YES):(NO));
}

BOOL ww_iOS8() {
    return (([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0)? (YES):(NO));
}

BOOL ww_iOS9() {
    return (([[[UIDevice currentDevice] systemVersion] floatValue] < 9.0)? (YES):(NO));
}

BOOL ww_preiOS7() {
    return (([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0)? (YES):(NO));
}
BOOL ww_preiOS8() {
    return (([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0)? (YES):(NO));
}
BOOL ww_preiOS9() {
    return (([[[UIDevice currentDevice] systemVersion] floatValue] < 9.0)? (YES):(NO));
}

BOOL ww_afteriOS7() {
    return (([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)? (YES):(NO));
}
BOOL ww_afteriOS8() {
    return (([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)? (YES):(NO));
}
BOOL ww_afteriOS9() {
    return (([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)? (YES):(NO));
}
BOOL ww_ipad() {
    return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad);
}
BOOL ww_iphone() {
    return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone);
}
BOOL ww_ipod() {
    return ([[[UIDevice currentDevice] model] isEqualToString:@"iPod touch"]);
}

BOOL ww_iPhone5SE() {
    return [[UIScreen mainScreen] bounds].size.width == 320.0f && [[UIScreen mainScreen] bounds].size.height == 568.0f;
}

BOOL ww_iPhone6_6s() {
    return [[UIScreen mainScreen] bounds].size.width == 375.0f && [[UIScreen mainScreen] bounds].size.height == 667.0f;
}

BOOL ww_iPhone6Plus_6sPlus() {
    return [[UIScreen mainScreen] bounds].size.width == 414.0f && [[UIScreen mainScreen] bounds].size.height == 736.0f;
}
// 判断是否有摄像头权限:
BOOL ww_cameraAccessible() {
    return [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo] == AVAuthorizationStatusRestricted || [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo] == AVAuthorizationStatusDenied?(NO):(YES);
}
// 获取 APP版本号
BOOL ww_appVersion() {
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}

// 获取 APP build version
NSString* ww_buildVersion() {
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
}

// 获取 APP名称
NSString* ww_appName() {
    
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
}

NSInteger ww_screenWidth() {
    return [UIScreen mainScreen].bounds.size.width;
}

NSInteger ww_screenHeight() {
    return [UIScreen mainScreen].bounds.size.height;
}

// temp 路径:
NSString * ww_pathTemp() {
    return NSTemporaryDirectory();
}
// Document 路径:
NSString * ww_pathDocument() {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
}
// Cache 路径
NSString * ww_pathCache() {
    return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
}

// alert 弹框
void ww_showAlert(NSString *title, NSString *msg) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show];
}


// 清空 某个 View 的所有子 view
void ww_removeSubviews(UIView *view) {
    [view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
}
// 开始设备自动锁屏
void ww_unLockScreen() {
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}

void ww_lockScreen() {
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}

// 如果文件夹不存在，创建该文件夹
void ww_createFolderIfNotExsit(NSString *folderPath) {
    BOOL isDir = NO;
    BOOL isDirExist = [[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:&isDir];
    if(!(isDirExist && isDir)) {
        BOOL bCreateDir = [[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir){
            NSLog(@"创建保存视频文件夹失败");
        }
    }
}

// 如果存在某文件，就删除该文件:
void ww_deleteFileIfExists(NSString *filePath) {
    NSError *saveError;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        [fileManager removeItemAtPath:filePath error:&saveError];
        if (saveError) {
            NSLog(@"删除文件出错：%@",filePath);
        }
    }
    
}


// APP主窗口  APP主导航控制器
UIWindow* ww_glWindow() {
    return [[[UIApplication sharedApplication] delegate] window];
}

UIViewController *ww_rootVC() {
    return [[[[UIApplication sharedApplication] delegate] window] rootViewController];
}
NSUserDefaults * ww_ww_glUserDefaults() {
    return [NSUserDefaults standardUserDefaults];
}
NSNotificationCenter* ww_glNotificationCenter() {
    return [NSNotificationCenter defaultCenter];
}

// 判断当前语言
NSString* ww_glLanguage() {
    return [[NSLocale preferredLanguages] firstObject];
}

UIFont* ww_font(NSInteger size) {
    return [UIFont systemFontOfSize:size];
}

UIFont* ww_fontBold(NSInteger size) {
    return [UIFont boldSystemFontOfSize:size];
}

UIFont* ww_fontWithName(NSString *fontName, NSInteger fontSize) {
    return [UIFont fontWithName:fontName size:fontSize];
}

NSURL* ww_url(NSString *urlString) {
    return [NSURL URLWithString:urlString];
}

NSURL* ww_fileUrl(NSString *path) {
    return [NSURL fileURLWithPath:path];
}

UIImage* ww_image(NSString *imageName) {
    return [UIImage imageNamed:imageName];
}

NSString* ww_bundlePath(NSString* name, NSString* type) {
    return [[NSBundle mainBundle] pathForResource:name ofType:type];
}

void ww_configBrightness(CGFloat brightness) {
    [[UIScreen mainScreen] setBrightness: brightness];
}
// 屏幕亮度相关:
CGFloat ww_brightness() {
    return [[UIScreen mainScreen] brightness];
}

// 对url进行百分号编码
NSString * ww_urlEncode(NSString *stringUrl) {
    return [stringUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

// 跳转到产品详情界面(跳转到appStore 应用) example:__gotoAppStore_descPage(444934666)
void ww_gotoAppStore_descPage(NSInteger productId)  {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%ld",(long)productId]]];
}

// 跳转到产品评论界面(跳转到appStore 应用) example: __gotoAppStore_commentPage(444934666)
void ww_gotoAppStore_commentPage(NSInteger productId) {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%ld&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8",(long)productId]]];
}


// 去除 字符串首尾空格和换行符
NSString * ww_stringCropBlank(NSString *string){
    return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

// 裁切图片
UIImage * ww_stretchImg(UIImage *image) {
    return [image stretchableImageWithLeftCapWidth:image.size.width/3.0 topCapHeight:image.size.height/3.0]?:[UIImage new];
}
#define MTBStretchImgCustom(image,w,h) [(image) stretchableImageWithLeftCapWidth:(image.size.width*(w)) topCapHeight:image.size.height*(h)]?:[UIImage new]

// 加载本地文件
UIImage * ww_imageFromFile(NSString *file, NSString *type) {
    return [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:file ofType:type]];
    
}
NSArray* ww_arrayFromFile(NSString *file, NSString *type) {
    return [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:file ofType:type]];
}

NSDictionary* ww_dicFromFile(NSString *file, NSString *type) {
    return [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle]pathForResource:file ofType:type]];
}

NSString * ww_stringConcat(NSString *str1, NSString *str2){
    return [NSString stringWithFormat:@"%@%@",str1,str2];
}

// 是否是视网膜屏幕
BOOL ww_retina() {
    return [UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO;
}

@end
